package ru.dc.gui.swing;

import javax.swing.table.AbstractTableModel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <pre>
 * User: Penkov Vladimir
 * Date: 09.11.2010
 * Time: 13:56:54
 * </pre>
 */
public class SearchSpyTableModel extends AbstractTableModel {

    private List<String> results = new ArrayList<String>();
    private Map<String, Integer> resultsCount = new HashMap<String, Integer>();
    private String[] columnNames = {
            "Запрос",
            "Количество"
    };

    public int getRowCount() {
        return results.size();
    }

    public int getColumnCount() {
        return columnNames.length;
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        return columnIndex==1 ? Integer.class : String.class;
    }

    @Override
    public String getColumnName(int column) {
        return columnNames[column];
    }

    public Object getValueAt(int rowIndex, int columnIndex) {
        switch (columnIndex) {
            case 0 : return results.get(rowIndex);
            case 1 : return resultsCount.get(results.get(rowIndex));
        }
        return null;
    }

    public void addResult(String result) {
        int index = results.indexOf(result);
        if (index>=0) {
            int i = resultsCount.get(result);
            i++;
            resultsCount.put(result, i);
            fireTableCellUpdated(index, 1);
        }
        else {
            results.add(result);
            resultsCount.put(result, 1);
            fireTableRowsInserted(getRowCount()-1, getRowCount()-1);
        }
    }

}
